<template>
  <div class="view-wrapper">
    <div class="btn-group">
      <el-button v-if="!isCapturing" type="primary" @click="startCapture">开始分享</el-button>
      <el-button v-else type="primary" @click="stopCapture">停止分享</el-button>
    </div>
    <video ref="video" autoplay></video>
    <div class="log-wrapper">
      <strong>Log:</strong>
      <ul>
        <li
          v-for="log in logList"
          :key="log.timestamp"
          :class="logClassName(log.type)"
        >
          {{ log.msg }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScreenCapture',
  data () {
    return {
      isCapturing: false,
      logList: []
    }
  },
  mounted () {
    this.videoElem = this.$refs.video
  },
  methods: {
    startCapture () {
      this.stopCapture()
      const displayMediaOptions = {
        audio: {
          echoCancellation: true, // 回声消除
          noiseSuppression: true, // 噪声抑制
          sampleRate: 44100 // 音频采样率
        },
        video: {
          cursor: 'always', // 指示是否捕获鼠标光标: always-一直捕获、motion-运动时捕获、never-不捕获
          logicalSurface: false // 捕获应该包括源的屏幕外区域
        }
      }
      navigator.mediaDevices.getDisplayMedia(displayMediaOptions).then(stream => {
        this.videoElem.srcObject = stream
        this.dumpOptionsInfo()
        this.isCapturing = true
      }).catch(err => {
        this.logList.push({
          type: 'error',
          msg: `Error: ${err}`
        })
      })
    },
    dumpOptionsInfo () {
      const videoTrack = this.videoElem.srcObject.getVideoTracks()[0]
      this.logList.push({
        type: 'info',
        msg: `Track settings: ${JSON.stringify(videoTrack.getSettings(), null, 2)}`
      })
      this.logList.push({
        type: 'info',
        msg: `Track constraints:: ${JSON.stringify(videoTrack.getConstraints(), null, 2)}`
      })
    },
    stopCapture () {
      if (this.videoElem.srcObject) {
        const tracks = this.videoElem.srcObject.getTracks()
        tracks.forEach(track => track.stop())
        this.videoElem.srcObject = null
        this.isCapturing = false
      }
    },
    logClassName (type) {
      let className = ''
      switch (type) {
      case 'info':
        className = 'info'
        break
      case 'warn':
        className = 'warn'
        break
      case 'error':
        className = 'error'
        break
      default:
        className = ''
      }
      return className
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-group {
  margin-bottom: 10px;
}

video {
  width: 100%;
  border: 1px solid #999;
}

.log-wrapper {
  margin-top: 10px;

  .error {
    color: #f00;
  }

  .warn {
    color: #ffa500;
  }

  .info {
    color: #006400;
  }
}
</style>
